import Taro, { Component } from '@tarojs/taro'
import {View, Image, Text, ScrollView} from '@tarojs/components'
import {connect} from "@tarojs/redux";
import { AtButton, AtIcon, AtInput, AtTag, AtCheckbox, AtModal } from 'taro-ui'
import {asyncCreatAddress, asyncUpdateAddress, asyncDeleteAddress, asyncGetAddress} from '../../api/address'
import './edit.styl'

@connect(({ user, shop }) => ({
  user, shop
}), (dispatch) => ({

}))
class Address extends Component {
  constructor () {
    super(...arguments)
    this.state = this.initialState
  }
    config = {
    navigationBarTitleText: '管理收货地址'
  }
  get initialState() {
    return {
      editId: null, // 被编辑的地址id
      shop_id: null, // 店铺id
      tag: '',
      address: '',
      village: '', // 小区名
      latitude: null,
      longitude: null,
      detail: '',
      contact: '',
      tel: '',
      gender: ['male'], // 性别 male 男; female 女

      // 删除提示
      deleteAddressModalShow: false
    };
  }

  // 下拉刷新
  onPullDownRefresh () {
    Taro.stopPullDownRefresh()
  }

  // 重置状态
  resetState () {
    this.setState(this.initialState);
  }
  // 输入联系人
  handleContactChange (val) {
    this.setState({
      contact: val
    })
  }
  // 手机号
  handleTelChange (val) {
    this.setState({
      tel: val
    })
  }
  // 门牌号
  handleDetailChange (val) {
    this.setState({
      detail: val
    })
  }
  // 性别
  handleGenderChange (value) {
    this.setState({
      gender: [value]
    })
  }
  // 选择地址前准备
  beforeChooseLocation () {
    // 查看用户的已授权
    Taro.getSetting({}).then(set => {
      console.log('用户已授权信息')
      // 如果用户已授权位置信息
      if (set.authSetting['scope.userLocation']) {
        this.chooseLocation()
      } else {
        Taro.authorize({
          scope: 'scope.userLocation'
        }).then(() => {
          console.log('用户授权 scope.userLocation')
          this.chooseLocation()
        })
      }
    }).catch(err => console.log(err))
  }

  // 选择地址
  chooseLocation () {
    Taro.chooseLocation({}).then((loc) => {
      console.log(loc)
      this.setState({
        address: loc.address,
        latitude: loc.latitude,
        longitude: loc.longitude,
        village: loc.name
      })
    })
  }
  // 标签
  toggleTag ({name}) {
    this.setState({
      tag: this.state.tag === name ? '' : name
    })
  }
  // 关闭当前页 需要在来源页指定来源
  closeCurrentPage () {
    Taro.navigateBack({ delta: 1 })
  }

  // 删除地址
  deleteAddress () {
    this.setState({deleteAddressModalShow: true})
  }
  // 删除地址取消
  deleteAddressCancel () {
    this.setState({deleteAddressModalShow: false})
  }
  // 删除地址确认
  deleteAddressConfirm () {
    const {editId} = this.state
    const {token} = this.props.user
    this.setState({deleteAddressModalShow: false})
    asyncDeleteAddress(token, editId).then(({status}) => {
      Taro.showToast({
        title: status ? '删除成功' : '删除失败',
        icon: 'none'
      }).then(() => {
        this.closeCurrentPage()
      })
    })
  }

  // 提交
  submit () {
    const {tag, address, village, latitude, longitude, detail, contact, tel, gender, editId} = this.state
    const {token} = this.props.user
    const {shop_id} = this.props.shop
    if (!contact) {
      Taro.showToast({
        title: '请填写收货人',
        icon: 'none'
      })
      return
    }

    if (!tel) {
      Taro.showToast({
        title: '请填写收货人电话',
        icon: 'none'
      })
      return
    }

    if (!address) {
      Taro.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return
    }

    if (!detail) {
      Taro.showToast({
        title: '请填写具体地址',
        icon: 'none'
      })
      return
    }

    if (editId) {
      asyncUpdateAddress(token,
        {address_id: editId, shop_id: this.state.shop_id, address, village, gatenum: detail, truename: contact, phone: tel, latitude, longitude, gender: gender[0] === 'male' ? '先生' : '女士', is_default: '0', tag}
        ).then(({status, msg}) => {
          Taro.showToast({
            title: status ? '修改成功' : msg,
            icon: 'none'
          }).then(() => {
            if (status) {
              this.closeCurrentPage()
            }
          })
      })
    } else {
      asyncCreatAddress(token,
        {address, shop_id, village, gatenum: detail, truename: contact, phone: tel, latitude, longitude, gender: gender[0] === 'male' ? '先生' : '女士', is_default: '0', tag}
      ).then(({status, msg}) => {
        Taro.showToast({
          title: status ? '添加成功' : msg,
          icon: 'none'
        }).then(() => {
          if (status) {
            this.closeCurrentPage()
          }
        })
      })
    }
  }

  componentWillReceiveProps (nextProps) {
    console.log(this.props, nextProps)
  }

  componentWillMount () {
    const edit = this.$router.params.edit
    const {token} = this.props.user
    if (edit !== 'new') {
      this.setState({
        editId: edit
      })
      // 加载地址详情
      asyncGetAddress(token, edit).then(({data, status}) => {
        // TODO 对错误的处理
        if (status) {
          this.setState({
            tag: data.tag,
            address: data.address,
            shop_id: data.shop_id,
            village: data.village, // 小区名
            latitude: data.lnglat.split(',')[1],
            longitude: data.lnglat.split(',')[0],
            detail: data.gatenum,
            contact: data.truename,
            tel: data.phone,
            gender: [data.gender === '先生' ? 'male' : 'female'] // 性别 male 男; female 女
          })
        }
      })
    }
  }

  componentWillUnmount () {
    this.resetState()
  }

  componentDidShow () { }

  componentDidHide () { }

  render () {
    const {contact, tel, detail, gender, address, tag, editId, toastText, toastOpen, deleteAddressModalShow} = this.state
    const renderTags = ['家', '公司', '学校'].map((name, index) => {
      return ( <AtTag key={index} active={name === tag} name={name} className='tag' onClick={this.toggleTag.bind(this)}>{name}</AtTag>)
    })
    return (
      <View className='address'>
        <ScrollView
          className='list'
          enableBackToTop
          scrollY
          scrollWithAnimation
          scrollTop='0'
        >
          {/*联系人*/}
          <AtInput
            name='contact'
            title='联系人'
            type='text'
            placeholder='输入联系人'
            value={contact}
            onChange={this.handleContactChange.bind(this)}
          />
          <View className='gender-checkbox'>
            <AtCheckbox
              className='gender-option'
              options={[{value: 'male', label: '先生'}]}
              selectedList={gender}
              onChange={this.handleGenderChange.bind(this, 'male')}
            />
            <AtCheckbox
              className='gender-option'
              options={[{value: 'female', label: '女士'}]}
              selectedList={gender}
              onChange={this.handleGenderChange.bind(this, 'female')}
            />
          </View>
          {/*手机号*/}
          <AtInput
            name='tel'
            border={false}
            title='手机号'
            type='phone'
            placeholder='手机号'
            value={tel}
            onChange={this.handleTelChange.bind(this)}
          />
          {/*地址选择*/}
          <View className='address-select' onClick={this.beforeChooseLocation.bind(this)}>
            <Text className='label'>收货地址</Text>
            {address ? <Text className='value'>{address}</Text> : <Text className='placeholder'>点击选择</Text>}
            <AtIcon className='arrow' value='chevron-right' size='16' color='#B2B2B2' />
          </View>
          {/*门牌号*/}
          <AtInput
            name='detail'
            title='门牌号'
            type='text'
            placeholder='例：16号楼2单元1501室'
            value={detail}
            onChange={this.handleDetailChange.bind(this)}
          />
          {/*设为常用标签*/}
          <View className='tag-set'>
            <Text className='label'>设为常用地址</Text>
            <View className='tags'>
              {renderTags}
            </View>
          </View>
        </ScrollView>
        <View className='bottom'>
          {editId && <AtButton type='secondary' className='del btn' onClick={this.deleteAddress.bind(this)}>删除</AtButton>}
          <AtButton type='primary' className='add btn' onClick={this.submit.bind(this)}>{editId ? '保存' : '新增'}</AtButton>
        </View>
        <AtModal
          isOpened={deleteAddressModalShow}
          title='删除提示'
          cancelText='取消'
          confirmText='确认'
          onClose={this.deleteAddressCancel.bind(this)}
          onCancel={this.deleteAddressCancel.bind(this)}
          onConfirm={this.deleteAddressConfirm.bind(this)}
          content='确认删除该地址'
        />
      </View>
    )
  }
}

export default Address
